import { _decorator, AudioSource, CircleCollider2D, Collider2D, Component, Contact2DType, director, IPhysics2DContact, Node, RigidBody, RigidBody2D, Vec2, Vec3 } from 'cc';
import { audioControl } from './audioControl';
import { heiziControl } from './heiziControl';

const { ccclass, property } = _decorator;

@ccclass('ballController')
export class ballController extends Component {

  @property({ type: Number })
  speed: number = 50
  @property({ type: String })
  direction: string = 'left'
  audio: audioControl = null
  //是否落地了
  touchedGround: boolean = false
  start() {
    this.shot(this.direction)
    this.getComponent(CircleCollider2D).on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this)
    this.audio = this.node.getParent().getChildByName('audio').getComponent(audioControl)
  }
  onBeginContact(self: Collider2D, other: Collider2D, contact: IPhysics2DContact) {

    if (other.tag === 3 && !this.touchedGround) {
      //小黑子血条 -1
      other.node.getComponent(heiziControl).die()
    }
    if (other.tag === 2) {
      //落地 篮球失效
      this.touchedGround = true
      this.node.getComponent(CircleCollider2D).sensor  = false//可穿过
      this.audio.ballVoice()
      this.die()
    }
  }
  update(dt: number) {

  }
  shot(dir: string) {
    this.getComponent(RigidBody2D).linearVelocity = new Vec2(this.direction === 'left' ? (-this.speed) : this.speed, 7)
  }
  die() {
    this.schedule(() => {
      this.node.destroy()
    }, 3)
  }
 
}


